import React from 'react';
import { Radio, Input, Button } from 'antd';
import { validatePirce } from '../helper';
import styles from './index.less';

const Filter = ({ title, checked, chooseClick, calculateCB, onChange }, ref) => {
  // 就是暴露给父组件的方法
  React.useImperativeHandle(ref, () => ({
    /**
     * 表单校验
     * @returns Array
     */
    valid: () => {
      let messages = new Array();
      // 选中状态需要校验价格
      if (checked) {
        (Number.isNaN(price) || !price) && messages.push('价格');
      }
      !province && messages.push('名称');
      return messages;
    },
    clear: () => {
      setPrice('');
      setProvince('');
    },
    updatePrice: (newPrice) => {
      setPrice(newPrice);
    },
  }));
  // 计算按钮loading
  const [loading, setLoading] = React.useState(false);
  /** 表单值 */
  const [price, setPrice] = React.useState('');
  const [province, setProvince] = React.useState('');

  React.useEffect(() => setPrice(''), [checked]);
  React.useEffect(() => onChange({ price, province }), [price, province]);

  return (
    <div className={styles.container}>
      <Radio className="radio" checked={checked} onClick={chooseClick}>
        {title}
      </Radio>
      <Input.Group size="small" compact>
        <Input
          style={{ width: '100px' }}
          value={province}
          onChange={(e) => setProvince(e.target.value)}
        />
        <div className={styles.divider}>|</div>
        <span className={styles.price}>价格</span>
        <Input
          disabled={!checked}
          value={price}
          style={{ width: '100px' }}
          onChange={(e) => setPrice(validatePirce(e.target.value))}
        />
      </Input.Group>
      <div className={styles.calculate}>
        <Button disabled={!checked} type="link" loading={loading} onClick={calculateCB}>
          计算
        </Button>
      </div>
    </div>
  );
};

export default React.forwardRef(Filter);
